package Day11;

import java.util.concurrent.locks.ReentrantLock;

//通过lock实现死锁
public class TestDeadLock2 {
    ReentrantLock lock1 = new ReentrantLock();
    ReentrantLock lock2 = new ReentrantLock();
    public void test1(){
        lock1.lock();
        System.out.println("线程1获取了lock1的锁，等待lock2");
        lock2.lock();
        System.out.println("线程1获取了lock1和lock2的锁");
        lock2.unlock();
        System.out.println("线程1释放了lock2的锁");
        lock1.unlock();
        System.out.println("线程1释放了lock1的锁");
    }

    public void test2(){
        lock2.lock();
        System.out.println("线程2获取了lock2的锁，等待lock1");
        lock1.lock();
        System.out.println("线程2获取了lock2和lock1的锁");
        lock1.unlock();
        System.out.println("线程2释放了lock1的锁");
        lock2.unlock();
        System.out.println("线程2释放了lock2的锁");
    }

    public static void main(String[] args) {
        TestDeadLock2 tdl = new TestDeadLock2();
        new Thread(()->{
            tdl.test1();
        }).start();
        new Thread(()->{
            tdl.test2();
        }).start();
    }
}
